package pl.jtb.ctl.tabory.h2.engine;

import org.apache.log4j.Logger;
import org.h2.tools.Server;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

public class Activator implements BundleActivator {

	private final Logger log = Logger.getLogger(Activator.this.getClass());

	private Server embeddedServer;
	
	private long backupPeriod = 5;

	public void start(BundleContext context) throws Exception {
		try {
			String symbolicName = context.getBundle().getSymbolicName();
			log.info("Starting bundle: " + symbolicName);
			long lastBackupInDays = BackupUtils.getLastBackupInDays();
			if (lastBackupInDays > backupPeriod){
				BackupUtils.doBackup();
			}
			embeddedServer = Server.createTcpServer().start();
			log.info(this.embeddedServer.getStatus());
			log.info("Bundle started OK. DB server status: " + embeddedServer.getStatus());
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

	public void stop(BundleContext context) throws Exception {
		try {
			String symbolicName = context.getBundle().getSymbolicName();
			log.info("Stopping bundle: " + symbolicName);
			embeddedServer.stop();
			log.info("H2 DB status: " + this.embeddedServer.getStatus());
			log.info("Bundle stopped OK: " + symbolicName);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

}
